package test.marui.com.mytest.view.layerView.view;

import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.IdRes;
import android.util.SparseArray;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import test.marui.com.mytest.R;

/**
 * Created by MR on 2019/1/21.
 */
class ViewHolder {

    private AnyLayer mLayer;
    private FrameLayout mContainer;
    private FrameLayout mContentWrapper;
    private ImageView mIvBackground;

    private SparseArray<View> views;
    private SparseArray<AnyLayer.OnLayerClickListener> onLayerClickListeners;

    ViewHolder(AnyLayer layer, FrameLayout container) {
        mLayer = layer;
        mContainer = container;
        mContentWrapper = container.findViewById(R.id.fl_content_wrapper);
        mIvBackground = container.findViewById(R.id.iv_background);
    }

    public FrameLayout getmContainer() {
        return mContainer;
    }

    public ImageView getmIvBackground() {
        return mIvBackground;
    }

    public FrameLayout getmContentWrapper() {
        return mContentWrapper;
    }

    public void recycle() {
        if (mIvBackground.getDrawable() instanceof BitmapDrawable) {
            BitmapDrawable drawable = (BitmapDrawable) mIvBackground.getDrawable();
            drawable.getBitmap().recycle();
        }
    }

    public <T extends View> T getView(@IdRes int viewId) {
        if (views == null) {
            views = new SparseArray<>();
        }

        if (views.indexOfKey(viewId) < 0) {
            T view = mContainer.findViewById(viewId);
            views.put(viewId, view);
            return view;
        }
        return (T) views.get(viewId);
    }

    public void bindClick() {
        if (onLayerClickListeners == null)
            return;

        for (int i = 0; i < onLayerClickListeners.size(); i++) {
            int id = onLayerClickListeners.keyAt(i);
            final AnyLayer.OnLayerClickListener listener = onLayerClickListeners.valueAt(i);
            getView(id).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onClick(mLayer,v);
                }
            });
        }

    }

    public void addOnClickListener(AnyLayer.OnLayerClickListener listener, @IdRes int viewId, @IdRes int... viewIds) {
        if (onLayerClickListeners == null) {
            onLayerClickListeners = new SparseArray<>();
        }

        if (onLayerClickListeners.indexOfKey(viewId) < 0) {
            onLayerClickListeners.put(viewId, listener);
        }

        if (viewIds != null && viewIds.length > 0) {
            for (int id : viewIds) {
                if (onLayerClickListeners.indexOfKey(id) < 0) {
                    onLayerClickListeners.put(id, listener);
                }
            }
        }

    }

}
